import React, { Component } from "react";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import { Card, Button, Icon, Input, message, Tag, Modal, Radio, Select } from "antd";
import { addFile, editFile, getFileInfo } from "@/services/knowledgeFile";
import styles from './knowledgeGather.less';
import { cancelKnowledgeCollect, postGenerateQuestions } from '@/services/knowledgeGather';
import { getModelList } from '@/services/assistantCenter';

const InputGroup = Input.Group;

class PreviewFile extends Component {
	constructor(props) {
		super(props);
		this.state = {
			isShowTitle: false,
			title: '',
			visibleSelectPage: false,
			visibleNextStep: false,
			btnLoading: false,
			checked: true,
			url: '',
			pdfUrl: '',
			pages: [null, null],
			pageList: [],
			perNumber: 10,
			cancelLoading: false,

            modelList: [],
			modelId: '',

		};
	}

	componentDidMount() {
		this._init_();
	}

	_init_ = () => {
		const { location: { query: { docId, docPath } } } = this.props;
		this.setFilePdfBlod(decodeURI(docPath))
	}

	setFilePdfBlod = url => {
		let that = this;
		let path = fileUrl + url;
		console.log(path);
		let xhr = new XMLHttpRequest();
		xhr.open('GET', path, true);
		xhr.responseType = 'blob'; //将response的格式设置为blob
		xhr.onreadystatechange = function () {
			if (xhr.readyState === 4) {
				if (xhr.status === 200) {
					that.setState({ url: window.URL.createObjectURL(xhr.response) }, () => {
						that.setState({ pdfUrl: '/pdfjs/web/viewer.html?file=' + encodeURIComponent(that.state.url) })
					})
				}
			};
		};
		xhr.send();
	};

	info = async id => {
		let res = await getFileInfo({ id });
		this.setState({ title: res.docTitle });
	}

	getAddPage = () => {
		let { pages, pageList } = this.state;
		pageList.unshift(pages);
		this.setState({ pages: [null, null], pageList });
	}

	onPageChange = (e, type, index) => {
		let { pages, pageList } = this.state;
		if (type >= 0) {
			pageList[type][index] = e.target.value;
		} else {
			pages[index] = e.target.value;
		};
		this.setState({ pages, pageList });
	}

	getDelPage = (index) => {
		let { pageList } = this.state;
		pageList = pageList.filter((i, j) => j != index);
		this.setState({ pageList });
	}

	getModelData = async () => {
        let res = await getModelList();
        console.log(res);
        this.setState({ modelList: res });
    }

	render() {
		const { match: { params: { id }, }, route, location: { params, query } } = this.props;
		const { isShowTitle, title, btnLoading, visibleNextStep, visibleSelectPage, pdfUrl, cancelLoading, modelList } = this.state;
		let BtnClassNextStep = {
			backgroundColor: "#FFFFFF",
			color: '#3E5BFF',
			borderColor: '#6478FF',
			marginRight: 10
		};
		let BtnClassSelectPage = {
			backgroundColor: "#FFFFFF",
			color: '#000000A6',
			borderColor: '#AAA',
			marginRight: 10
		};

		return (
			<Card bordered={false}>
				<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', margin: '-8px 0 16px' }}>
					<div style={{ fontWeight: 'bold', fontSize: '15px' }}>
						<Button onClick={this.backRouter} loading={cancelLoading}>取消采编</Button>
					</div>
					<div>
						<Button onClick={this.openSelectPageModal} style={BtnClassSelectPage}>选择自定义页码</Button>
						<Button onClick={this.openNextStepModal} style={BtnClassNextStep}>下一步生成问题</Button>
					</div>
				</div>
				<div style={{ height: 'calc(100vh - 275px)' }}>
					<iframe src={pdfUrl} width="100%" height="100%" frameborder="0" />
				</div>

				<Modal
					title={<span style={{ fontWeight: 'bold' }}>根据当前范围生成问题</span>}
					visible={visibleSelectPage}
					centered
					onOk={this.saveSelectPage}
					onCancel={this.cancelSelectPage}
					footer={[
						<Button type="danger" onClick={this.cancelSelectPage}>取消</Button>,
						<Button type="primary" onClick={this.saveSelectPage}>确认</Button>,
					]}
				>
					<p style={{ display: 'flex' }}>
						<span>文档范围：</span>
						<Radio.Group onChange={this.onPageTypeChange} value={this.state.checked}>
							<Radio value={true}>全部页</Radio>
							<Radio value={false}>自选页</Radio>
						</Radio.Group>
					</p>
					{!this.state.checked ? (
						<p style={{ display: 'flex' }}>
							<span>填写页码：</span>
							<span style={{ flex: 1 }}>
								<span>请填写所需的开始页码和结束页码，支持添加多组页码范围。若仅选择单页，则开始页码与结束页码填写相同数值即可。</span>
								<br />
								<span>
									<span style={{ margin: '8px 0', display: 'inline-block', lineHeight: 0 }}>
										<span style={{ display: 'flex', gap: 20, alignItems: 'center' }}>
											<InputGroup compact style={{ width: 'unset' }}>
												<Input style={{ width: 100, textAlign: 'center' }} suffix="页" value={this.state.pages[0]} onChange={e => this.onPageChange(e, -1, 0)} />
												<Input
													style={{
														width: 38,
														borderLeft: 0,
														paddingTop: '2px',
														pointerEvents: 'none',
														backgroundColor: '#fff',
													}}
													placeholder="至"
													disabled
												/>
												<Input className={styles.inputOrYe} suffix="页" value={this.state.pages[1]} onChange={e => this.onPageChange(e, -1, 1)} />
											</InputGroup>
											<Icon type="plus-square" style={{ fontSize: '18px' }} onClick={this.getAddPage} />
										</span>
										<br />
									</span>
									{this.state.pageList && this.state.pageList.map((item, index) => (
										<span key={index} style={{ margin: '8px 0', display: 'inline-block', lineHeight: 0 }}>
											<span style={{ display: 'flex', gap: 20, alignItems: 'center' }}>
												<InputGroup compact style={{ width: 'unset' }}>
													<Input style={{ width: 100, textAlign: 'center' }} suffix="页" value={item[0]} onChange={e => this.onPageChange(e, index, 0)} />
													<Input
														style={{
															width: 38,
															borderLeft: 0,
															paddingTop: '2px',
															pointerEvents: 'none',
															backgroundColor: '#fff',
														}}
														placeholder="至"
														disabled
													/>
													<Input className={styles.inputOrYe} suffix="页" value={item[1]} onChange={e => this.onPageChange(e, index, 1)} />
												</InputGroup>
												<Icon type="delete" style={{ fontSize: '18px' }} onClick={() => this.getDelPage(index)} />
											</span>
											<br />
										</span>
									))}
								</span>
							</span>
						</p>
					) : null}
				</Modal>

				<Modal
					title={<span style={{ fontWeight: 'bold' }}>根据当前范围生成问题</span>}
					visible={visibleNextStep}
					centered
					onOk={this.saveNextStep}
					onCancel={this.cancelNextStep}
					footer={[
						<Button type="danger" onClick={this.cancelNextStep}>取消</Button>,
						<Button type="primary" loading={btnLoading} onClick={this.saveNextStep}>下一步</Button>,
					]}
				>
					<p>
						<span>每页生成问题数&nbsp;&nbsp;&nbsp;</span>
						<Input style={{ width: '64px' }} value={this.state.perNumber} onChange={this.setCount} />
						<span>&nbsp;&nbsp;&nbsp;条</span>
					</p>
					<p style={{ color: '#faad14' }}>这个步骤耗时时间较长，需耐心等待</p>

					
					<div>
						<span>选择大模型&nbsp;&nbsp;&nbsp;</span>
						<Select placeholder="请选择大模型" onChange={this.onModelChange} style={{ width: '160px' }}>
							{modelList.map((item, index) => (
								<Select.Option value={item.id} key={index}>{item.name}</Select.Option>
							))}
						</Select>
					</div>
				</Modal>
			</Card>
		);
	}

	openSelectPageModal = () => {
		this.setState({ visibleSelectPage: true })
	}

	saveSelectPage = () => {
		let { pages, pageList } = this.state;
		this.cancelSelectPage();
	}

	cancelSelectPage = () => {
		this.setState({ visibleSelectPage: false })
	}

	openNextStepModal = () => {
		this.setState({ visibleNextStep: true }, () => {
			this.getModelData();
		})
	}

	onModelChange = value => {
		this.setState({ modelId: value })
	}

	backRouter = () => {
		Modal.confirm({
			title: '确定取消当前文档的采编',
			okText: '确定',
			okType: 'danger',
			cancelText: '取消',
			onOk: async () => {
				this.setState({ cancelLoading: true })
				let res = await cancelKnowledgeCollect();
				console.log(res);
				if (res.code === 0) {
					this.setState({ cancelLoading: false })
					const { dispatch } = this.props;
					let pathname = "/knowledgeDesign/knowledgeCollect";
					dispatch(routerRedux.push({ pathname }));
				} else {
					this.setState({ cancelLoading: false })
				}
			},
			onCancel() {
				console.log('取消操作！！！');
			},
		});
	}

	onPageTypeChange = e => {
		this.setState({ checked: e.target.value });
	}

	cancelNextStep = () => {
		this.setState({ visibleNextStep: false, btnLoading: false })
	}

	setCount = e => {
		this.setState({ perNumber: e.target.value })
	}

	saveNextStep = e => {
		e.stopPropagation();
        e.preventDefault();
		const { location: { query: { docId } } } = this.props;
		let { perNumber, checked, pageList, pages, modelId } = this.state;
		pageList.unshift(pages);
		pageList = pageList.reverse();
		let list = [];
		pageList.map((item, index) => {
			if (item[0] != null && item[1] != null) {
				list.push(item)
			}
			if (item[0] == null && item[1] != null) {
				list.push([item[1], item[1]])
			}
			if (item[0] != null && item[1] == null) {
				list.push([item[0], item[0]])
			}
		});
		if (!checked && list && list.length <= 0) {
			return message.error('请输入自定义页码')
		};
		let obj = {
			type: 1,
			perNumber,
			isAllChoose: checked,
			pageList: !checked ? list : undefined,
			docId,
		};
		if (modelId && modelId != '') {
			obj.modelId = modelId;
		} else {
			return message.error('请先选择模型')
		};
		this.setState({ btnLoading: true }, async () => {
			let res = await postGenerateQuestions(obj);
			console.log(res);
			if (res.code == 0) {
				// 	message.info(res.msg);
				this.setState({ btnLoading: false }, () => {
					this.cancelNextStep()
					this.nextRouter()
				});
			}
			// else {
			// 	this.setState({ btnLoading: false });
			// }
		})
	}

	nextRouter = () => {
		const { dispatch } = this.props;
		let pathname = "/knowledgeDesign/knowledgeCollect/generateQuestion";
		dispatch(routerRedux.push({ pathname }));
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(PreviewFile);
